/*
 * I write in my free time, for personal using
 * when i fell proud of it, i will give it to public
 * now,have nothing more to say
 */
package com.quangtin3.msg;

import com.quangtin3.utils.Utils;
import java.io.ByteArrayOutputStream;

/**
 * present message and control data between tunnels, tunnel and agent
 * @author quanghx
 */
public class Msg {

    public static final int TYPE_DATA = 0;
    public static final int TYPE_COMAND = 1;
    public static final int TYPE_RESPONSE = 2;
    public static final int CMD_DATA = 0;
    public static final int CMD_CONNECT = 1;
    public static final int CMD_CLOSE = 2;
    private final static int HEAD_LENGTH = 4 * 4;
    private int type;
    private int cmd;
    private int tunnel;
    private byte[] data;

    public Msg(int type, int cmd, int channel, byte[] data) {
        this.type = type;
        this.cmd = cmd;
        this.tunnel = channel;
        this.data = data;
    }

    public int getType() {
        return type;
    }

    public int getTunnel() {
        return tunnel;
    }

    public int getCmd() {
        return cmd;
    }

    @Override
    public String toString() {
        return "msg <datalenght=" + data.length + ",type=" + type +
                ",cmd=" + cmd + ",tunnel=" + tunnel + ">";
    }

    /**
     * pack data send and receive with agent
     * @return data only
     */
    public byte[] getData() {
        return data;
    }

    /**
     * pack data to send between tunll
     * @return message data and control data
     */
    public byte[] pack() {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length + HEAD_LENGTH);
        try {
            bos.write(Utils.getByte(data.length));
            bos.write(Utils.getByte(type));
            bos.write(Utils.getByte(cmd));
            bos.write(Utils.getByte(tunnel));
            bos.write(data);
        } catch (Exception e) {
        //never
        }
        return bos.toByteArray();
    }
}
